package sms_code

import (
	"context"
	"git.myscrm.cn/golang/stark/v4"
	"gorm.io/gorm"
)

type SmsCodeRepository struct {
}

// NewSmsCodeRepository 构造函数
func NewSmsCodeRepository() SmsCodeRepositoryIface {
	return &SmsCodeRepository{}
}

// SaveSmsCode 保存验证码记录
func (s *SmsCodeRepository) SaveSmsCode(ctx context.Context, data *SmsCodePo) (int64, error) {
	db := stark.MySQLConn.Get(ctx)
	result := db.Table(SmsCodePo{}.TableName()).Save(data)
	if result.Error != nil {
		stark.Logger.Errorf(ctx, "SaveSmsCode save data : %+v, error: %+v", data, result.Error)
		return 0, nil
	}
	return data.Id, nil
}

// 根据手机号获取最新验证码
func (s *SmsCodeRepository) GetCodeByMobile(ctx context.Context, mobile string, scene int32) (*SmsCodePo, error) {
	db := stark.MySQLConn.Get(ctx)
	smsCode := &SmsCodePo{}
	err := db.Table(SmsCodePo{}.TableName()).
		Where("mobile=?", mobile).
		Where("scene=?", scene).
		Where("is_deleted = 0").Order("send_time desc").First(&smsCode).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return smsCode, nil
}
